<?php

namespace Zch\LishangLaravelShop\Data\Goods\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Zch\LishangLaravelShop\Data\Goods\Observers\CategoryObserver;
use Zch\LishangLaravelShop\Data\Goods\Models\Category;
use Zch\LishangLaravelShop\Data\Goods\Models\Model;
use Zch\LishangLaravelShop\Data\Goods\Util\ObserverUtil;

class GoodsServiceProvider extends ServiceProvider
{
    public function register()
    {
        //dd('goodsserver');
        $this->mergeConfigFrom(__DIR__ . '/../Config/goods.php', 'data.goods');

        $this->mergeConfigFrom(__DIR__.'/../Config/observer.php', 'data.goods-observer');

        // 预习内容
        // 注册
        // Illuminate\Database\Eloquent\Concerns\HasEvents::observe();

        // 所有注册的事件绑定 Illuminate\Events\Dispatcher 中的 $listeners属性

        // 查找并执行
        // Illuminate\Database\Eloquent\Concerns\HasEvents::fireModelEvent();

        //批量新增的问题

    }

    public function boot()
    {
        //注册模型观察者，作用是绑定模型操作前后需要的事件，跟mysql触发器一样的功能
        //Category::observe(CategoryObserver::class);
        //Model::observes();//有问题，还不能使用
        $this->loadObserver();
        $this->loadGoodsConfig();
        $this->loadMigrations();
    }

    public function loadObserver()
    {
        ObserverUtil::observes();
        // Category::observe(CategoryObserver::class);
        // Goods::observe(GoodsObserver::class);
    }

    public function loadGoodsConfig()
    {
        // 根据默认连接的信息去database.php配置分属于goods组件的连接信息

        $goodsConnectName = 'database.connections.'.config('data.goods.database.connection.name');//得到的值为“database.connections.goods”
        //config('data.goods.database.connection.type') 得到的值为“mysql”
        config(
            // Arr::dot(config('database.connections.mysql', []), 'database.connections.goods.')
            Arr::dot(config('database.connections.'.config('data.goods.database.connection.type'), []), $goodsConnectName.'.')
        );
        // 在把goods组件的单独信息 放到 database中的goods连接的信息
        config(
            // Arr::dot(config('data.goods.database.goods', []), 'database.connections.goods.')
            Arr::dot(config('data.goods.database.'.config('data.goods.database.connection.name'), []), $goodsConnectName.'.')
        );
    }

    public function loadMigrations()
    {
        if($this->app->runningInConsole()){
            $this->loadMigrationsFrom(__DIR__ . '/../Database/migrations');
        }
    }
}
